<?php

$inc_core = realpath(dirname(__FILE__) . '/../inc/inc_core.inc');
require_once $inc_core;
use teia\webdev\php\core as teia;

function display_pwd_req_form($txt_array=NULL, $err_msg='') {
	echo "\n<div class=\"pwd_help_form\">\n";
	// display error message, if any
	if (!empty($err_msg)) {
		echo "<p class='err_msg'>$err_msg</p>\n";
	}
	// call password request form
	teia\FunctionPool::display_pwd_req_form($txt_array);
	// end forms
	echo "</div>\n";
}

function handle_pwd_req_form() {	
	if (teia\FunctionPool::validate_post_vars(array('recaptcha_challenge_field', 'recaptcha_response_field', 'email'))) {
		$challenge = $_POST['recaptcha_challenge_field'];
		$response = $_POST['recaptcha_response_field'];
		$email = $_POST['email'];
		
		if (teia\FunctionPool::validate_email($email)) {
			$pass = teia\FunctionPool::verify_recaptcha_response($challenge, $response);
			if ($pass) {
				// verify email
				$pass = teia\User::verify_usr_email($email);
				if ($pass) {
					// create password reset email
					
					// redirect user
					$msg = urlencode("The instructions to reset your password were sent to '$email'");
					$queries = array('err_msg' => $msg);
					teia\FunctionPool::goto_url('/login.php', $queries);
				} else {
					display_pwd_req_form(null, "There is no account associated with the email '$email'!");
				}
			} else {
				display_pwd_req_form(null, 'Wrong answer, please try again!');
			}	
		} else {
			display_pwd_req_form(null, 'Invalid email!');
		}
	} else {
		display_pwd_req_form(null, 'You must fill out all fields!');
	}
}
?>

<!-- Internal style -->
<style type="text/css">
<!--

#err_msg {
text-align: center;
border-style: solid;
border-width: medium;
border-color: red;
display: block;
}

#usr_pwd_req_form {
	margin-left: 100px;
	margin-right: 100px;
}

div {
	width: 70%;
	display: block;
}

.input_field {
	width: 15em;
	text-align: left;
	margin-left: 0.5em;
}

-->
</style>

<?php

// decide what and how to display
if (isset($_POST['form_name'])) {
	$form_name = $_POST['form_name'];
	if ($form_name == 'pwd_req_form') {
		// process form
		handle_pwd_req_form();
	} else {
		// unexpected form, ignore it and display form
		display_pwd_req_form();
	}
} else {
	// first pass, no form submitted
	display_pwd_req_form();
}
?>